package com.avasthi.cli.twitter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;

public class AmazonInstantVideoReviewMain {

	static Set<AmazonInstantVideoReview> reviews = new HashSet<AmazonInstantVideoReview>();
	static File basedir;
	static Random r = new Random();
	public AmazonInstantVideoReviewMain() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		if (args.length == 0) {
			System.out.println("Usage: java "
					+ AmazonInstantVideoReviewMain.class.getCanonicalName()
					+ " reviewfile");
			System.exit(0);
		}
		File tmp = new File(args[0]);
		basedir = new File(tmp.getParent());
		float minScore = 100000;
		float minHelpfulness = 100000;
		float maxScore = -100;
		float maxHelpfulness = -100;
		try {
			FileInputStream fis = new FileInputStream(args[0]);
			BufferedReader br = new BufferedReader(new InputStreamReader(fis,
					Charset.forName("UTF-8")));
			String line;
			String productId = null;
			String productTitle = null;
			float productPrice = 0;
			String reviewUserId = null;
			String reviewProfileName = null;
			float reviewHelpfulness = 0;
			float reviewScore = 0;
			long reviewTime = 0;
			String reviewSummary = null;
			String reviewText = null;
			int count = 0;
			while ((line = br.readLine()) != null) {
				// Deal with the line
				line = line.trim();
				if (line.isEmpty()) {
					AmazonInstantVideoProduct product = new AmazonInstantVideoProduct(
							productId, productTitle, productPrice);
					AmazonInstantVideoReview review = new AmazonInstantVideoReview(
							product, reviewUserId, reviewProfileName,
							reviewHelpfulness, reviewScore, reviewTime,
							reviewSummary, reviewText);
					reviews.add(review);
					minScore = Math.min(minScore, reviewScore);
					maxScore = Math.max(maxScore, reviewScore);
					minHelpfulness = Math
							.min(minHelpfulness, reviewHelpfulness);
					maxHelpfulness = Math
							.max(maxHelpfulness, reviewHelpfulness);
				} else {
					StringTokenizer st = new StringTokenizer(line, ":");
					String key = st.nextToken().trim().toLowerCase();
					String value = "";
					if (st.hasMoreTokens()) {

						value = st.nextToken().trim();
					}
					if (key.equals("product/productid")) {
						productId = value;
					} else if (key.equals("product/title")) {
						productTitle = value;
					} else if (key.equals("product/price")) {
						try {

							productPrice = Float.parseFloat(value);
						} catch (NumberFormatException nex) {
							productPrice = 0;
						}
					} else if (key.equals("review/userid")) {
						reviewUserId = value;

					} else if (key.equals("review/profilename")) {
						reviewProfileName = value;
					} else if (key.equals("review/helpfulness")) {
						if (value.isEmpty()) {
							reviewHelpfulness = -1;
						} else {

							StringTokenizer st1 = new StringTokenizer(value,
									"/");
							float f1 = Float.parseFloat(st1.nextToken());
							float f2 = Float.parseFloat(st1.nextToken());
							if (f2 >= 5) {
								reviewHelpfulness = f1 / f2;
							} else {
								reviewHelpfulness = -1;
							}
						}
					} else if (key.equals("review/score")) {
						reviewScore = Float.parseFloat(value);
					} else if (key.equals("review/time")) {
						reviewTime = Long.parseLong(value);
					} else if (key.equals("review/summary")) {
						reviewSummary = value;
					} else if (key.equals("review/text")) {
						reviewText = value;
					}
				}

			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		createDatafiles();
	}

	static private void createDatafiles() {
		for (AmazonInstantVideoReview r : reviews) {
			if (isReviewClear(r.helpfulness)) {

				String subdir = getSubdir(r.score, r.helpfulness);
				File dir = new File(basedir, subdir);
				if (!dir.isDirectory()) {
					dir.mkdirs();
				}
				try {
					File f = new File(dir, r.product.id + "-" + r.userId);
					if (!f.canWrite()) {
						f.createNewFile();
						f.setWritable(true);
					}
					PrintWriter writer = new PrintWriter(f, "UTF-8");
					writer.println(r.summary);
					writer.println(r.text);
					writer.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
	}
	static private String getSubdir(float score, float helpful) {
		int v = r.nextInt() % 5;
		String subdir = "/train";
		if (v == 0 || v == 1) {
			subdir = "/test";
		}
		subdir += ("/" + getHelpfulString(helpful) + "-" + getScoreString(score));
		return subdir;
	}
	static private boolean isReviewClear(float helpful) {
		return ((helpful >= 0 && helpful <= 0.1) || (helpful > 0.9 && helpful <= 1.0));
	}

	static private String getScoreString(float score) {
		int s = (int) score;
		switch (s) {
		case 0:
			return "Zero";
		case 1:
			return "One";
		case 2:
			return "Two";
		case 3:
			return "Three";
		case 4:
			return "Four";
		case 5:
			return "Five";
		}
		return "Unknown";
	}

	static private String getHelpfulString(float helpful) {
		if (helpful < 0) {
			return "Unknown";
		} else if (helpful >= 0 && helpful <= 0.1) {
			return "Unhelpful";
		} else if (helpful > 0.9 && helpful <= 1.0) {
			return "Helpful";
		}
		return "Unknown";
	}

}
